Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', '../shared/ux');

Ext.require([
    'Ext.form.*',
    'Ext.data.*',
    'Ext.layout.container.Column',
    'Ext.tab.TabPanel',
    'Ext.ux.GMapPanel'
]);

Ext.require([
    'Ext.window.*',
    'Ext.ux.GMapPanel'
]);


/*!
 * Ext JS Library 3.3.1
 * Copyright(c) 2006-2010 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
Ext.onReady(function(){

    Ext.QuickTips.init();

    var bd = Ext.getBody();
    
	function getExtraParams(){
		var s = document.location.search.split('?');
		var a = {};
		if(s.length > 1){
			a = Ext.urlDecode(s[1]);
		}
		var b = {
				memberEmail: Ext.util.Cookies.get('memberEmail'),
				memberPassword: Ext.util.Cookies.get('memberPassword')

		};

		return Ext.merge(a,b);
		
	};
    
	Ext.regModel('Category', {
		fields: [
			{name: 'idCategory', type: 'int'},
			{name: 'name',  type: 'string'}
		]
	});

	Ext.regModel('Item', {
		fields: [
			{name: 'idItem', type: 'int'},
			{name: 'categoriesId', type: 'string'},
			{name: 'categoriesName', type: 'string'},
			{name: 'name',  type: 'string'},
			{name: 'description',  type: 'string'},
			{name: 'latitude',  type: 'float'},
			{name: 'longitude',  type: 'float'},
			{name: 'street',  type: 'string'},
			{name: 'city',  type: 'string'},
			{name: 'state',  type: 'string'},
			{name: 'country',  type: 'string'},
			{name: 'zipcode',  type: 'string'},
			{name: 'phone',  type: 'string'},
			{name: 'cellphone',  type: 'string'},
			{name: 'email',  type: 'string'},
			{name: 'skype',  type: 'string'},
			{name: 'url',  type: 'string'}
		],
		hasMany  : {model: 'Category', name: 'categories'}

	});

	var categoryStore = new Ext.data.Store({
		model: 'Category',
		proxy: {
			type: 'ajax',
			url : '../../cattolica-web/category/list?leaf=true',
			reader: {
				type: 'json',
				root: 'categories',
                idProperty: 'idCategory'
			}
		}
	});  

	function getExtraParams(){
		var s = document.location.search.split('?');
		var a = {};
		if(s.length > 1){
			a = Ext.urlDecode(s[1]);
		}
		var b = {
				memberEmail: Ext.util.Cookies.get('memberEmail'),
				memberPassword: Ext.util.Cookies.get('memberPassword')

		};

		return Ext.merge(a,b);
	};

	function getGeocodeName(){
		var items = fp.getForm().getValues();
		return items.name;
	}

	function getGeocodeAddress(){
		var items = fp.getForm().getValues();
		if(items.street == null || items.street == ''){
			return 'Cattolica, Italia';
		}

		return items.street + ', ' + items.city + ', ' + items.country;
	}

	function onAddressChange(){
		var gmap = Ext.getCmp('gmap');
		if(gmap){
			//point, marker, clear, center, listeners){
			//gmap.addMarker(
			gmap.getMap().clearOverlays();

			gmap.geoCodeLookup(getGeocodeAddress());
		}
	}

	function showMap(){
		//var mapp = Ext.create('Ext.Window', {
		var mapp = Ext.create('Ext.panel.Panel', {
			id: 'mapp',
			border:false,
			width:450,
			height:450,
			items:[
				{
					id: 'gmap',
					xtype: 'gmappanel',
					zoomLevel: 16,
					gmapType: 'map',
					mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
					mapControls: ['GSmallMapControl','GMapTypeControl','NonExistantControl'],
					setCenter: {
						geoCodeAddr: getGeocodeAddress(),
						marker: {title: getGeocodeName()}
					}
				}
			]
		});
		//mapp.show();
		mapp.render(document.body);
	}

    var fp = Ext.create('Ext.form.FormPanel', {
		id: 'fp',
        border:false,
        width: 350,
        fieldDefaults: {
            labelWidth: 75,
            msgTarget: 'side'
        },
        defaults: {
            anchor: '100%'
        },
        reader : new Ext.data.JsonReader({
		    model: 'Item',
   		    idProperty: 'idItem'
		}),

        items: [
            {
                xtype: 'hidden',
                fieldLabel: 'idItem',
                name: 'idItem'
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Nome',
                anchor: '100%',
                name: 'name',
                allowBlank: false
            },
            {
                xtype: 'combo',
                fieldLabel: 'Categoria',
                anchor: '100%',
                name: 'idCategory',
				id: 'idCategory',
                allowBlank: false,
				store: categoryStore,
			    displayField: 'name',
			    valueField: 'idCategory',
				editable: false,
				multiSelect: true
            },
            {
                xtype: 'textarea',
                anchor: '100%',
                fieldLabel: 'Descrizione',
                name: 'description'
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Via',
                anchor: '100%',
                name: 'street',
                allowBlank: false
            },
            {
                xtype: 'hidden',
                fieldLabel: 'City',
                anchor: '100%',
                name: 'city',
                allowBlank: false
            },
            {
                xtype: 'hidden',
                fieldLabel: 'State',
                anchor: '100%',
                name: 'state',
                allowBlank: false
            },
            {
                xtype: 'hidden',
                fieldLabel: 'Country',
                anchor: '100%',
                name: 'country',
                allowBlank: false,
                id: 'country'
            },
            {
                xtype: 'hidden',
                fieldLabel: 'Zipcode',
                anchor: '100%',
                name: 'zipcode',
                id: 'zipcode'
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Telefono',
                anchor: '100%',
                name: 'phone',
                id: 'phone'
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Cellulare',
                anchor: '100%',
                name: 'cellphone',
                id: 'cellphone'
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Email',
                anchor: '100%',
                name: 'email',
                id: 'email',
                vtype:'email'
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Skype',
                anchor: '100%',
                name: 'skype',
                id: 'skype'
            },
            {
                xtype: 'textfield',
                fieldLabel: 'Sito web',
                anchor: '100%',
                name: 'url',
                id: 'url'
            }

           
            ],
                   
        buttons: [{
            text: 'Salva',
            disabled: true,
            formBind: true,
			handler: function() {
				var form = this.up('form').getForm();
				if (form.isValid()) {
					form.submit({
						url: '../../cattolica-web/item/edit',
						params: getExtraParams(),
	                    submitEmptyText: false,
						success: function(form, action) {
						   document.location = 'list.html';
						},
						failure: function(form, action) {
							Ext.Msg.alert('Failed', action.response.statusText);
						}
					});
				}
			}
        },
		{
            text: 'Verifica mappa',
			handler: function() {
				onAddressChange();
			}
        },	
		{
            text: 'Esci',
			handler: function() {
				history.back();
			}
        }]
    });

	categoryStore.load({
		callback: function(records, operation, success) {

			fp.getForm().load({
				url: '../../cattolica-web/item/get?' + Ext.urlEncode(getExtraParams()),
				success: function(form, action) {
					var idCategoryCombo = Ext.getCmp('idCategory');
					var r = form.reader;
					var rd = r.rawData;
					var c = rd.categories;

					idCategoryCombo.setValue(rd.categoriesId);
					idCategoryCombo.setRawValue(rd.categoriesName);
					showMap();
				}
			});
		
		}
	});


    fp.render(document.body);


});

